#include "oled.h"
#include "display.h"
#include "rc38.h"


type_oled oled_data = {DISABLE};
const uint8_t oled_num[] = "0123456789ABCDEF";

uint8_t oled_wait_even(I2C_Event_TypeDef even)
{
  uint8_t t=0;
  for(t=0;t<OLED_TIMEOUT&&!I2C_CheckEvent(even);t++);
  return t==OLED_TIMEOUT ? 1 : 0;
}

uint8_t oled_wait_flag(I2C_Flag_TypeDef flag)
{
  uint8_t t=0;
  for(t=0;t<OLED_TIMEOUT&&I2C_GetFlagStatus(flag);t++);
  return t==OLED_TIMEOUT ? 1 : 0;
}

uint8_t oled_write(uint8_t addr, uint8_t* data, uint8_t len)
{
  if(oled_wait_flag(I2C_FLAG_BUSBUSY)) return 1;
  I2C_GenerateSTART(ENABLE);
  if(oled_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 2;
  I2C_Send7bitAddress(OLED_ADDR, I2C_DIRECTION_TX);
  if(oled_wait_even(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) return 3;
  I2C_SendData(addr);
  while(len--)
  {
    if(oled_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 4;
    I2C_SendData(*data++);
  }
  if(oled_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 5;
  I2C_GenerateSTOP(ENABLE);
  return 0;
}

uint8_t oled_write_command(uint8_t cmd)
{
  return oled_write(0x00, &cmd, 1);
}

uint8_t oled_write_data(uint8_t *data, uint8_t len)
{
  return oled_write(0x40, data, len);
}

uint8_t oled_addr(uint8_t x, uint8_t y)
{
  uint8_t rel;
  rel = oled_write_command(0xb0|y);
  if(rel) return rel;
  rel = oled_write_command(0x10|x>>4);
  if(rel) return rel;
  rel = oled_write_command(x&0x0f);
  return rel;
}
  
void oled_clear(uint8_t clr)
{
  uint8_t data[128];
  for(uint8_t i=0;i<128;i++)
  {
    data[i] = clr;
  }
  for(uint8_t y=0;y<8;y++)
  {
    oled_addr(0, y);
    oled_write_data(data, 128);
  }
}

void oled_init(void)
{
  uint8_t init_data[] = {0x81, 0xff, 0xd9, 0xf1, 0xdb, 0x30, 0xc8, 0xa1, 0x8d, 0x14, 0xaf};
  for(uint8_t i=0;i<11;i++)
  {
    oled_write(0x00, init_data+i, 1); 
  }
  oled_clear(0);
}

void oled_task(void)
{
  static uint8_t tt=0, data[24], rc;
 /* uint8_t temp[3];
  oled_addr(80, 1);
  temp[0] = oled_num[tt>>4];
  temp[1] = oled_num[tt&0x0f];
  temp[2] = 0;
  //ascii_get_str(temp, data);
  oled_write_data(data, 12);
  tt++;*/
  oled_data.flag = DISABLE;
  
  for(uint8_t i=0;i<3;i++)
  {
    oled_addr(36*i+15, 6);
    display_geth(i+1, data);
    oled_write_data(data, 22);
    oled_addr(36*i+15, 7);
    display_getl(i+1, data);
    oled_write_data(data, 22);
  }
  /*
  rc = rc38_get();  
  temp[0] = oled_num[rc>>4];
  temp[1] = oled_num[rc&0x0f];
  temp[2] = 0;
  //ascii_get_str(temp, data);
  oled_addr(12, 3);
  oled_write_data(data, 12);*/
}

void oled_fun(void)
{
  if(oled_data.flag == DISABLE)return;
  oled_task();
}
 
void oled_timer(void)
{
  if(++oled_data.timer==200)
  {
    oled_data.timer=0;
    oled_data.flag = ENABLE;
  }
}
